<template>
  <div class="system-bg">
    <el-card class="user-card" shadow="hover">
      <div slot="header" class="card-header-horizontal">
        <div class="header-title">成员审核管理</div>
        <div class="header-btn-group">
          <el-button class="refresh-btn" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card pending">
              <div class="stat-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.pending || 0 }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card approved">
              <div class="stat-icon">
                <i class="el-icon-check"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.approved || 0 }}</div>
                <div class="stat-label">已通过</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card rejected">
              <div class="stat-icon">
                <i class="el-icon-close"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.rejected || 0 }}</div>
                <div class="stat-label">已拒绝</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card total">
              <div class="stat-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.total || 0 }}</div>
                <div class="stat-label">总计</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索工具栏 -->
      <el-form :inline="true" :model="queryParams" class="search-bar" @submit.native.prevent>
        <el-form-item label="审核状态">
          <el-select v-model="queryParams.status" placeholder="全部" size="small">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="PENDING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属家族">
          <el-select v-model="queryParams.clanId" placeholder="全部" size="small">
            <el-option label="全部" value="" />
            <el-option v-for="clan in clanList" :key="clan.id" :label="clan.name" :value="clan.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 审核列表 -->
      <el-table
        v-loading="loading"
        :data="auditList"
        border
        stripe
        class="audit-table"
        highlight-current-row
      >
        <el-table-column prop="id" label="编号" width="80" align="center" />
        <el-table-column label="申请人" width="150" align="center">
          <template slot-scope="scope">
            <div class="user-info">
              <el-avatar
                v-if="scope.row.proposer_user_name"
                :src="scope.row.proposer_avatar"
                :size="32"
              ></el-avatar>
              <span class="user-name">{{ scope.row.proposer_user_name || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="成员名称" width="120" align="center" />
        <el-table-column label="性别" width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.gender === 'M' ? 'primary' : 'danger'" size="mini">
              {{ scope.row.gender === 'M' ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关系类型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.relationship === 'CHILD' ? 'success' : 'warning'" size="mini">
              {{ scope.row.relationship === 'CHILD' ? '子女' : '配偶' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="clan_name" label="所属家族" width="120" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              size="mini"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="提交时间" width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="scope">
            <div class="action-btn-group">
              <el-button size="mini" class="detail-btn" @click="handleView(scope.row)">查看详情</el-button>
              <el-button
                v-if="scope.row.status === 'PENDING'"
                size="mini"
                class="approve-btn"
                @click="handleApprove(scope.row)"
              >通过</el-button>
              <el-button
                v-if="scope.row.status === 'PENDING'"
                size="mini"
                class="reject-btn"
                @click="handleReject(scope.row)"
              >拒绝</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.size"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="audit-pagination"
      />
    </el-card>

    <!-- 审核详情对话框 -->
    <el-dialog
      title="审核详情"
      :visible.sync="detailDialogVisible"
      width="800px"
      class="fade-dialog custom-dialog"
    >
      <div v-if="currentAudit" class="audit-detail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="申请人">{{ currentAudit.proposer_user_name }}</el-descriptions-item>
          <el-descriptions-item label="成员姓名">{{ currentAudit.name }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentAudit.gender === 'M' ? '男' : '女' }}</el-descriptions-item>
          <el-descriptions-item label="关系类型">{{ currentAudit.relationship === 'CHILD' ? '子女' : '配偶' }}</el-descriptions-item>
          <el-descriptions-item label="所属家族">{{ currentAudit.clan_name }}</el-descriptions-item>
          <el-descriptions-item label="关联成员">{{ currentAudit.parent_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ formatDate(currentAudit.birth_date) }}</el-descriptions-item>
          <el-descriptions-item label="去世日期">{{ formatDate(currentAudit.death_date) }}</el-descriptions-item>
          <el-descriptions-item label="籍贯" :span="2">{{ currentAudit.native_place || '-' }}</el-descriptions-item>
          <el-descriptions-item label="现住地址" :span="2">{{ currentAudit.current_address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="个人事迹" :span="2">{{ currentAudit.story || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="审核信息" :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(currentAudit.status)">
              {{ getStatusText(currentAudit.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDate(currentAudit.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="审核人">{{ currentAudit.auditor_user_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">{{ formatDate(currentAudit.updated_at) }}</el-descriptions-item>
          <el-descriptions-item label="审核备注" :span="2">{{ currentAudit.audit_remarks || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 审核处理对话框 -->
    <el-dialog
      title="审核处理"
      :visible.sync="auditDialogVisible"
      width="500px"
      class="fade-dialog custom-dialog"
    >
      <el-form :model="auditForm" label-width="100px" class="dialog-form">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditAction">
            <el-radio label="APPROVE">通过</el-radio>
            <el-radio label="REJECT">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核原因">
          <el-input
            v-model="auditForm.auditReason"
            type="textarea"
            :rows="4"
            placeholder="请输入审核原因"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAuditSubmit" :loading="auditSubmitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAuditList, getAuditDetail, processAudit, getAuditStats, getPendingCount } from '@/api/audit';
import { getClanList } from '@/api/clan';

export default {
  name: 'AuditPage',
  data() {
    return {
      loading: false,
      auditList: [],
      total: 0,
      detailDialogVisible: false,
      auditDialogVisible: false,
      currentAudit: null,
      clanList: [],
      stats: {
        pending: 0,
        approved: 0,
        rejected: 0,
        total: 0
      },
      auditForm: {
        id: null,
        auditAction: 'APPROVE',
        auditReason: '',
        auditorId: null
      },
      auditSubmitting: false,
      queryParams: {
        page: 1,
        size: 10,
        status: '',
        clanId: null,
        proposerUserId: null
      }
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    // 加载数据
    async loadData() {
      await Promise.all([
        this.getAuditList(),
        this.getStats(),
        this.getClanList()
      ]);
    },

    // 获取审核列表
    async getAuditList() {
      this.loading = true;
      try {
        const response = await getAuditList(this.queryParams);
        console.log('getAuditList',response)
        if (response && response.records) {
          this.auditList = response.records;
          this.total = response.total;
        } else {
          this.$message.error(response.msg || '获取审核列表失败');
        }
      } catch (error) {
        console.error('获取审核列表出错', error);
        this.$message.error('获取审核列表出错，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 获取统计数据
    async getStats() {
      try {
        const response = await getAuditStats();
        if (response.code === 0) {
          const statsData = response.data;
          this.stats = {
            pending: 0,
            approved: 0,
            rejected: 0,
            total: 0
          };

          statsData.forEach(item => {
            if (item.status === 'PENDING') this.stats.pending = item.count;
            else if (item.status === 'APPROVED') this.stats.approved = item.count;
            else if (item.status === 'REJECTED') this.stats.rejected = item.count;
            this.stats.total += item.count;
          });
        }
      } catch (error) {
        console.error('获取统计数据出错', error);
      }
    },

    // 获取家族列表
    async getClanList() {
      try {
        const response = await getClanList();
        if (response.code === 0) {
          this.clanList = response.data;
        }
      } catch (error) {
        console.error('获取家族列表出错', error);
      }
    },

    // 查看详情
    async handleView(row) {
      this.detailDialogVisible = true;
      this.currentAudit = row;
    },

    // 通过审核
    handleApprove(row) {
      this.currentAudit = row;
      this.auditForm = {
        id: row.id,
        auditAction: 'APPROVE',
        auditReason: '',
        auditorId: this.$store.state.user.id
      };
      this.auditDialogVisible = true;
    },

    // 拒绝审核
    handleReject(row) {
      this.currentAudit = row;
      this.auditForm = {
        id: row.id,
        auditAction: 'REJECT',
        auditReason: '',
        auditorId: this.$store.state.user.id
      };
      this.auditDialogVisible = true;
    },

    // 提交审核
    async handleAuditSubmit() {
      if (!this.auditForm.auditReason.trim()) {
        this.$message.warning('请输入审核原因');
        return;
      }

      this.auditSubmitting = true;
      try {
        const response = await processAudit(this.auditForm);
        if (response.code === 0) {
          this.$message.success('审核处理成功');
          this.auditDialogVisible = false;
          this.loadData();
        } else {
          this.$message.error(response.msg || '审核处理失败');
        }
      } catch (error) {
        console.error('审核处理出错', error);
        this.$message.error('审核处理出错，请稍后重试');
      } finally {
        this.auditSubmitting = false;
      }
    },

    // 搜索
    handleSearch() {
      this.queryParams.page = 1;
      this.getAuditList();
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        status: '',
        clanId: null,
        proposerUserId: null
      };
      this.getAuditList();
    },

    // 刷新
    handleRefresh() {
      this.loadData();
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.queryParams.page = 1;
      this.getAuditList();
    },

    // 当前页改变
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getAuditList();
    },

    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 'PENDING': return 'warning';
        case 'APPROVED': return 'success';
        case 'REJECTED': return 'danger';
        default: return 'info';
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'PENDING': return '待审核';
        case 'APPROVED': return '已通过';
        case 'REJECTED': return '已拒绝';
        default: return '未知';
      }
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '-';
      return new Date(date).toLocaleDateString('zh-CN');
    }
  }
};
</script>

<style scoped>
.system-bg {
  min-height: 80vh;
  background: linear-gradient(135deg, #f4f6fa 60%, #e0e7ff 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 0;
  animation: fadeIn 0.8s;
}

.user-card {
  width: 1100px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.10);
  background: rgba(255,255,255,0.95);
  transition: box-shadow 0.3s;
}

.card-header-horizontal {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
}

.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}

.header-btn-group {
  display: flex;
  align-items: center;
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}

.header-btn-group .el-button {
  margin-right: 8px;
  height: 34px;
  font-size: 15px;
  padding: 0 18px;
  display: flex;
  align-items: center;
}

.header-btn-group .el-button:last-child {
  margin-right: 0;
}

.refresh-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
}

.refresh-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}

/* 统计卡片样式 */
.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-card.pending {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #8b6914;
}

.stat-card.approved {
  background: linear-gradient(135deg, #52c41a, #73d13d);
  color: #135200;
}

.stat-card.rejected {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
  color: #820014;
}

.stat-card.total {
  background: linear-gradient(135deg, #6a82fb, #fc5c7d);
  color: #fff;
}

.stat-icon {
  font-size: 32px;
  margin-right: 16px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  font-weight: 500;
}

/* 搜索栏样式 */
.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: transparent;
  border-radius: 8px;
  border: none;
}

/* 表格样式 */
.audit-table {
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 18px;
}

.audit-table ::v-deep .el-table__row:hover {
  background: #f0f7ff !important;
  transition: background 0.2s;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
}

/* 操作按钮组样式 */
.action-btn-group {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 12px;
}

.action-btn-group .el-button {
  min-width: 55px;
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
  box-sizing: border-box;
}

.detail-btn {
  background: #fff;
  border: 1px solid #909399;
  color: #606266;
  border-radius: 6px;
  transition: all 0.2s;
}

.detail-btn:hover {
  background: #f4f6fa;
  color: #409EFF;
  border-color: #409EFF;
}

.approve-btn {
  background: #fff;
  border: 1px solid #52c41a;
  color: #52c41a;
  transition: all 0.2s;
}

.approve-btn:hover {
  background: #52c41a;
  color: #fff;
}

.reject-btn {
  background: #fff;
  border: 1px solid #ff4d4f;
  color: #ff4d4f;
  transition: all 0.2s;
}

.reject-btn:hover {
  background: #ff4d4f;
  color: #fff;
}

/* 分页样式 */
.audit-pagination {
  margin-top: 18px;
  text-align: right;
}

.audit-pagination ::v-deep .el-pager li {
  border-radius: 6px;
  transition: background 0.2s;
}

.audit-pagination ::v-deep .el-pager li.active {
  background: #6a82fb;
  color: #fff;
}

/* 对话框样式 */
.fade-dialog ::v-deep .el-dialog__wrapper {
  animation: fadeIn 0.4s;
}

.custom-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  background: #fafdff;
  padding-bottom: 0;
}

.dialog-form {
  padding: 12px 0 0 0;
}

.dialog-form ::v-deep .el-form-item {
  margin-bottom: 22px;
}

.dialog-footer {
  text-align: right;
  padding: 8px 0 8px 0;
}

.dialog-footer .el-button {
  min-width: 80px;
  border-radius: 6px;
  font-weight: 500;
  margin-left: 8px;
}

.dialog-footer .el-button--primary {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
}

.dialog-footer .el-button--primary:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}

.audit-detail {
  max-height: 600px;
  overflow-y: auto;
}

/* 状态标签样式 */
.el-tag {
  border-radius: 4px;
}

/* 描述列表样式 */
.el-descriptions {
  margin-bottom: 20px;
}

.el-descriptions__title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

/* 单选按钮组样式 */
.el-radio-group {
  display: flex;
  gap: 20px;
}

.el-radio {
  margin-right: 0;
}

/* 文本域样式 */
.el-textarea__inner {
  border-radius: 4px;
}

/* 加载状态 */
.el-loading-mask {
  border-radius: 8px;
}

/* 表格边框样式 */
.audit-table .el-table {
  border-radius: 8px;
  overflow: hidden;
}

.audit-table .el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards .el-col {
    margin-bottom: 16px;
  }

  .stat-card {
    padding: 16px;
  }

  .stat-icon {
    font-size: 24px;
    margin-right: 12px;
  }

  .stat-number {
    font-size: 20px;
  }

  .search-bar {
    padding: 12px;
  }

  .action-btn-group {
    flex-direction: column;
    gap: 8px;
  }

  .action-btn-group .el-button {
    width: 100%;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
